<template>
  <view class="index">
    <nut-row>
      <nut-col :span="12">
        <div class="space-title" @click="toShowRooms">
          {{ selectedRoom.name || "请选择房间" }}&nbsp;&nbsp;<nut-icon
            :name="showRooms ? 'arrow-up' : 'arrow-down'"
            size="10"
          ></nut-icon>
        </div>
      </nut-col>
      <nut-col :span="12">
        <nut-button
          plain
          type="primary"
          size="small"
          icon="plus"
          @click="toAddDevice"
          >添加设备</nut-button
        >
      </nut-col>
    </nut-row>
    <nut-popup
      position="top"
      :style="{ height: '50%', padding: '10px 10px' }"
      v-model:visible="showRooms"
    >
      <nut-row style="400px">
        <nut-col :span="8">
          <div style="min-width: 120px">
            <div v-for="r in rooms" :key="r.id">
              <nut-button
                plain
                :type="selectedRoom.id == r.id ? 'primary' : 'default'"
                @click="selectedRoomChange(r)"
                >{{ r.name }}</nut-button
              >
            </div>
            <nut-divider></nut-divider>
            <nut-button
              size="small"
              plain
              type="primary"
              icon="edit"
              @click="inManage = !inManage"
              >{{ inManage ? "完成" : "管理" }}</nut-button
            >
          </div>
        </nut-col>
        <nut-col :span="16">
          <nut-form v-if="inManage" v-model="editRoomForm">
            <nut-cell
              ><nut-button
                type="primary"
                plain
                size="small"
                icon="plus"
                @click="addNewRoom"
              ></nut-button
            ></nut-cell>
            <nut-form-item label="名称" label-width="30px">
              <input
                class="nut-input-text"
                v-model="editRoomForm.name"
                placeholder="请输入房间名"
                type="text"
              />
            </nut-form-item>
            <nut-row style="margin-top: 10px">
              <nut-col :span="12">
                <nut-button type="primary" size="small" @click="saveRoom"
                  >保存</nut-button
                >
              </nut-col>
              <nut-col :span="12">
                <nut-button type="primary" plain size="small">删除</nut-button>
              </nut-col>
            </nut-row>
          </nut-form>
        </nut-col>
      </nut-row>
    </nut-popup>

    <nut-grid v-if="devices.length > 0" :border="false">
      <nut-grid-item v-for="d in devices" :key="d.id">
        <device :data="d"></device>
      </nut-grid-item>
    </nut-grid>
    <nut-empty v-else description="暂无设备，快去添加吧"></nut-empty>
    <div style="height: 100px"></div>

    <nut-tabbar
      @tab-switch="pages.tabSwitch"
      :bottom="true"
      v-model:visible="active"
    >
      <nut-tabbar-item
        tab-title="首页"
        icon="home"
        :to="pages.home"
      ></nut-tabbar-item>
      <nut-tabbar-item
        tab-title="设备"
        icon="category"
        :to="pages.devices"
      ></nut-tabbar-item>
      <nut-tabbar-item
        tab-title="我的"
        icon="my"
        :to="pages.my"
      ></nut-tabbar-item>
    </nut-tabbar>
  </view>
</template>

<script>
import Taro from "@tarojs/taro";
import pages from "../../services/pageConfig";
import { reactive, toRefs, ref } from "vue";
import httpService from "../../services/httpService";
import userService from "../../services/userService";
import device from "../../components/device.vue";

export default {
  name: "Index",
  components: { device },
  unmounted() {
    httpService.removePullDevice("room", null);
  },
  setup() {
    const state = reactive();

    const active = 1;
    const rooms = ref([]);
    const devices = ref([]);

    const selectedRoom = ref({ id: "", name: "" });
    const editRoomForm = ref({ id: "", name: "" });
    const inManage = ref(false);

    //显示房间列表
    const showRooms = ref(false);
    function toShowRooms() {
      showRooms.value = !showRooms.value;
      if (showRooms.value) {
        getRooms();
      }
    }

    function getRooms() {
      let home = userService.currentHome();
      return httpService.get("/space/spaces/" + home.id).then((res) => {
        if (res.statusCode == 200) {
          rooms.value = res.data;
          if (rooms.value.findIndex((r) => r.id == selectedRoom.value.id) < 0) {
            let room = rooms.value[0];
            if (room) {
              selectedRoom.value = { id: room.id, name: room.name };
            }
          }
        }
      });
    }

    //使用第一个房间获取设备列表
    getRooms().then((res) => {
      getDevices();
    });

    function addNewRoom() {
      editRoomForm.value.id = "";
      editRoomForm.value.name = "";
    }

    function selectedRoomChange(value) {
      selectedRoom.value.id = value.id;
      selectedRoom.value.name = value.name;
      editRoomForm.value.id = value.id;
      editRoomForm.value.name = value.name;
      //切换房间
      if (!inManage.value) {
        showRooms.value = false;
        getDevices();
      }
    }

    function saveRoom() {
      let url = "/space/addSpace";
      if (editRoomForm.value.id) {
        url = "/space/saveSpace/" + editRoomForm.value.id;
      }

      httpService.post(url, { params: editRoomForm.value }).then((res) => {
        if (res.statusCode == 200) {
          Taro.showToast({
            title: "保存成功",
            icon: "success",
            duration: 2000,
          });
          getRooms();
        }
      });
    }

    //按房间获取设备列表
    function getDevices() {
      if (!selectedRoom.value.id) {
        Taro.showToast({
          title: "请先添加房间",
          icon: "error",
          duration: 2000,
        });
        return;
      }
      httpService
        .get("/space/myDevices/" + selectedRoom.value.id)
        .then((res) => {
          if (res.statusCode == 200) {
            //删除旧的拉取设备
            httpService.removePullDevice("room", null);
            devices.value = res.data;
            //添加新的拉取设备并开始拉取设备信息
            devices.value.forEach((d) => {
              httpService.addPullDevice("room", d.deviceId);
              httpService.pullDeviceInfo("room", d);
            });
          }
        });
    }

    function toAddDevice() {
      Taro.navigateTo({
        url:
          "/pages/device/add?spaceId=" +
          selectedRoom.value.id +
          "&spaceName=" +
          selectedRoom.value.name,
      });
    }

    return {
      state,
      active,
      showRooms,
      toShowRooms,
      addNewRoom,
      selectedRoom,
      editRoomForm,
      selectedRoomChange,
      saveRoom,
      inManage,
      devices,
      rooms,
      pages,
      toAddDevice,
    };
  },
};
</script>

<style lang="scss">
.space-title {
  font-size: 16px;
  text-align: center;
}
.device {
  max-width: 45vw;
  height: 180px;
  box-sizing: border-box;
  padding: 10px 10px 10px 10px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  box-shadow: 2px 2px 11px 0px rgba(50, 50, 50, 0.1);
  text-align: center;
  color: #333;
  img {
    max-width: 70%;
    max-height: 60%;
  }
  .name {
    width: 100%;
    font-size: 18px;
    margin-bottom: 10px;
  }
}

.state {
  height: 10px;
  width: 100%;
  border-top-right-radius: 10px;
  border-top-left-radius: 10px;
  // border-bottom: 1px solid rgba(170, 170, 170, 0.54);
  font-size: 8px;
  line-height: 12px;
  color: #fff;
  text-align: center;
}
.state.online {
  background-color: #0daf0170;
}
.state.offline {
  background-color: #98989870;
}
</style>
